/**
 * ZHU framework. Copyright 2012-, all rights reserved.
 *
 * $Id: DayController.java 46 2012-09-19 09:10:23Z zhuxiaopeng $
 * $Revision: 46 $
 * $Date: 2012-09-19 17:10:23 +0800 (三, 2012-09-19) $
 * $Author: zhuxiaopeng $
 */
package daily.web.file;

import static zhu.framework.web.WebUtility.*;

import java.io.*;
import java.util.*;

import javax.enterprise.context.*;
import javax.inject.*;

import org.primefaces.event.*;
import org.primefaces.model.*;

import zhu.framework.service.*;
import zhu.framework.web.*;
import zhu.framework.web.jsf.*;

import com.google.common.base.*;

import daily.entity.*;
import daily.service.*;

/**
 * <p>
 * </p>
 * 
 * @author $Author: zhuxiaopeng $
 * @version $Revision: 46 $ - $Date: 2012-09-19 17:10:23 +0800 (三, 2012-09-19) $
 */
@Named
@RequestScoped
public class FilesController extends ConversationalController {

	public List<Files> getFileList() {
		if (filesConversation.getFileList() == null) {
			filesConversation.setFileList(fileServiceImpl.getFileList());
		}
		return filesConversation.getFileList();
	}

	public void deleteFile(final Files selectedFile) {
		try {
			fileServiceImpl.deleteFile(selectedFile);
			getWebRequestContext().addMessage(new WebMessage(WebSeverity.INFO, "Succesful ", selectedFile.getFilename() + " is deleteded."));
			filesConversation.setFileList(null);
		} catch (final BusinessException e) {
			getWebRequestContext().addMessages(WebMessage.valueOf(e.getMessages()));
		}
	}

	public StreamedContent getDownfile(final Files selectedFile) {
		final InputStream stream = new ByteArrayInputStream(fileServiceImpl.getByteFile(selectedFile));
		return new DefaultStreamedContent(stream, selectedFile.getContentTyp(), selectedFile.getFilename(), "utf-8");
	}

	public void upload(final FileUploadEvent event) {
		final UploadedFile file = event.getFile();
		if (file != null && Strings.isNullOrEmpty(file.getFileName()) == false) {
			fileServiceImpl.saveFile(getServiceRequestContext(), file);
			getWebRequestContext().addMessage(new WebMessage(WebSeverity.INFO, "Succesful ", file.getFileName() + " is uploaded."));
			filesConversation.setFileList(null);
		}
	}

	@Inject
	private FilesServiceImpl fileServiceImpl;

	@Inject
	private FilesConversation filesConversation;
}
